// main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'element-plus/dist/index.css'
import NaiveUI from 'naive-ui'
import App from './App.vue'
import { useAppStore } from './stores/appStore'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import { ElMessage } from 'element-plus'
import router from './router/index'

// 全局路由守卫：/admin 路由需要登录，前台个人中心等页面也需要登录
router.beforeEach((to, from, next) => {
  const appStore = useAppStore()
  // 前台需要登录的页面路径
  const needLoginPaths = ['/profile', '/records', '/appointments']
  if (to.path.startsWith('/admin') && to.path !== '/admin/login') {
    if (!appStore.user.isLoggedIn) {
      return next('/admin/login')
    }
  } else if (needLoginPaths.includes(to.path)) {
    // 前台个人中心、就诊病历、预约信息等页面未登录拦截
    if (!appStore.user.isLoggedIn) {
      ElMessage.error('请先登录后再访问该页面')
      return next('/')
    }
  }
  next()
})

// 创建并挂载应用
const app = createApp(App)
// 创建Pinia实例
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

app.use(pinia)
app.use(router)
app.use(ElementPlus, {
  locale: zhCn
})
app.use(NaiveUI)
app.mount('#app')